package com.health.ts.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.ChannelTopic;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.serializer.GenericToStringSerializer;

import com.alibaba.fastjson.support.spring.GenericFastJsonRedisSerializer;
import com.health.ts.service.topic.RedisTopic1MessageListener;
import com.health.ts.service.topic.RedisTopic2MessageListener;
 
/**
 * redis配置类
 */
 
@Configuration
public class RedisConfig {
 
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        // 使用 GenericFastJsonRedisSerializer 替换默认序列化
        GenericFastJsonRedisSerializer genericFastJsonRedisSerializer = new GenericFastJsonRedisSerializer();
        // 设置key和value的序列化规则
        redisTemplate.setKeySerializer(new GenericToStringSerializer<>(Object.class));
        redisTemplate.setValueSerializer(genericFastJsonRedisSerializer);
        // 设置hashKey和hashValue的序列化规则
        redisTemplate.setHashKeySerializer(new GenericToStringSerializer<>(Object.class));
        redisTemplate.setHashValueSerializer(genericFastJsonRedisSerializer);
        // 设置支持事物
        redisTemplate.setEnableTransactionSupport(true);
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
    
    /**
     * Redis发布订阅消息监听器容器
     * @param connectionFactory
     * @return
     */
    @Bean
    RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) {
        RedisMessageListenerContainer container = new RedisMessageListenerContainer();
        container.setConnectionFactory(connectionFactory);
        //订阅了一个叫topic1和topic2 的通道，多通道
        container.addMessageListener(topic1MessageListener(), new ChannelTopic("topic1"));
        container.addMessageListener(topic2MessageListener(), new ChannelTopic("topic2"));
        //这个container 可以添加多个 messageListener
        return container;
    }
    
    @Bean("topic1MessageListener")
    RedisTopic1MessageListener topic1MessageListener() {
    	return new RedisTopic1MessageListener();
    }
    
    @Bean("topic2MessageListener")
    RedisTopic2MessageListener topic2MessageListener() {
    	return new RedisTopic2MessageListener();
    }
}